import eventBus from "@/eventBus";
import {
    debounce
} from "@/utils";
import defaultGif from "@/assets/default.gif";

let imgs = [];
export default {
    inserted(el, bindings) {
        const img = {
            dom: el,
            src: bindings.value,
        };
        imgs.push(img);
        setImages(imgs);
    },
    unbind(el) {
        imgs = imgs.filter((img) => img.dom !== el);
    }
}
eventBus.$on("mainScroll", debounce(handleScroll, 50));

function setImages() {
    for (const img of imgs) {
        setImage(img);
    }
}

function handleScroll() {
    setImages();
}

function setImage(img) {
    img.dom.src = defaultGif;
    //判断是否在可视区域
    const rect = img.dom.getBoundingClientRect();
    const clientHeight = document.documentElement.clientHeight;
    const height = rect.height || 150;
    if (rect.top >= -height && rect.top <= clientHeight) {
        // const tempImg = new Image();
        // tempImg.onload = function () {
        //     img.dom.src = img.src;
        // };
        // tempImg.src = img.src;
        img.dom.src = img.src;
        imgs = imgs.filter((i) => i !== img);
    }
    // imgs = imgs.filter((i) => i !== img);
}